package com.crm.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.crm.common.constant.Constants;
import com.crm.common.constant.HttpStatus;
import com.crm.common.constant.RedisConstants;
import com.crm.common.utils.Base64;
import com.crm.common.utils.IdUtils;
import com.crm.service.FunctionService;
import com.google.code.kaptcha.Producer;
import jakarta.annotation.Resource;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.FastByteArrayOutputStream;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import static com.crm.common.constant.HttpStatus.SUCCESS;

@Service
@Slf4j
@AllArgsConstructor
public class FunctionServiceImpl implements FunctionService {

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;


    @Override
    public void getSnowflake() {

    }

    /**
     * 获取验证码
     *
     * @return
     */
    @Override
    public HashMap<String, Object> getCode() {
        HashMap<String, Object> map = new HashMap<>();
        log.info("生成验证码");
        map.put("code", SUCCESS);
        map.put("msg", "生成验证码成功");
        map.put("captchaEnabled", true);

        // 保存验证码信息
        String uuid = IdUtils.simpleUUID();
        String verifyKey = RedisConstants.CAPTCHA_CODE_KEY + uuid;
        String capStr = null, code = null;
        BufferedImage image = null;

        String capText = captchaProducerMath.createText();
        capStr = capText.substring(0, capText.lastIndexOf("@"));
        code = capText.substring(capText.lastIndexOf("@") + 1);
        image = captchaProducerMath.createImage(capStr);
        redisTemplate.opsForValue().set(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", os);
        } catch (IOException e) {
            map.put("code", HttpStatus.ERROR);
            return map;
        }
        map.put("uuid", uuid);
        map.put("img", Base64.encode(os.toByteArray()));
        return map;
    }

    /**
     * 获取验证码
     *
     * @return
     */

    public HashMap<String, Object> getCodeByHuTool() {
        HashMap<String, Object> map = new HashMap<>();
        log.info("开始生成验证码....");
        map.put("code", SUCCESS);
        map.put("msg", "生成验证码成功");
        map.put("captchaEnabled", true);
        // 生成两个随机数并计算结果
        int num1 = (int) (Math.random() * 9) + 1;
        int num2 = (int) (Math.random() * 9) + 1;
        int result = num1 + num2;

        // 使用表达式创建验证码图片
        String expression = num1 + "+" + num2 + "=?";
        // 创建验证码图片
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 80);


        BufferedImage image = (BufferedImage) lineCaptcha.createImage(expression); // 直接用表达式生成图像

        // 保存结果到Redis
        String uuid = IdUtils.simpleUUID();
        String verifyKey = RedisConstants.CAPTCHA_CODE_KEY + uuid;
        redisTemplate.opsForValue().set(verifyKey, String.valueOf(result), Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);

        // 转换图片为Base64
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", os);
        } catch (IOException e) {
            map.put("code", HttpStatus.ERROR);
            map.put("msg", "验证码生成失败");
            return map;
        }
        map.put("uuid", uuid);
        map.put("img", Base64.encode(os.toByteArray()));
        map.put("expression", expression); // 可选返回用于前端显示
        return map;
    }
}
